<template>
  <div class="contract-review-container">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <el-form 
        :model="searchForm" 
        :inline="true" 
        class="search-form"
        label-width="120px"
      >
        <el-form-item label="合同编号">
          <el-input
            v-model="searchForm.contractNumber"
            placeholder="请输入合同编号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="客户代码">
          <el-input
            v-model="searchForm.customerCode"
            placeholder="请输入客户代码"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="客户名称">
          <el-input
            v-model="searchForm.customerName"
            placeholder="请输入客户名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        
        <el-form-item label="合同拟制时间">
          <el-date-picker
            v-model="searchForm.createDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        
        <el-form-item label="业务经理">
          <el-select
            v-model="searchForm.manager"
            placeholder="请选择业务经理"
            clearable
            filterable
            remote
            reserve-keyword
            :remote-method="handleManagerSearch"
            :loading="managerLoading"
            style="width: 200px"
          >
            <el-option 
              v-for="manager in managerOptions" 
              :key="manager.value" 
              :label="manager.label"
              :value="manager.value" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="合同拟制人">
          <el-select
            v-model="searchForm.creator"
            placeholder="请选择拟制人"
            clearable
            filterable
            remote
            reserve-keyword
            :remote-method="handleCreatorSearch"
            :loading="creatorLoading"
            style="width: 200px"
          >
            <el-option 
              v-for="creator in creatorOptions" 
              :key="creator.value" 
              :label="creator.label"
              :value="creator.value" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleSearch"
            :loading="loading"
          >
            <i class="fas fa-search"></i>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <i class="fas fa-redo"></i>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据列表区域 -->
    <el-card class="table-card" shadow="never">
      <!-- 表头标题 -->
      <div class="table-header">
        <div class="table-title">
          <i class="fas fa-file-contract"></i>
          合同审核列表
        </div>
        <div class="table-actions">
          <el-button 
            type="info" 
            @click="handleExport"
          >
            <i class="fas fa-file-excel"></i>
            导出数据
          </el-button>
        </div>
      </div>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        
        <el-table-column 
          prop="contractNumber" 
          label="合同编号" 
          width="150"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="customerCode" 
          label="客户代码" 
          width="120"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="customerType" 
          label="客户类型" 
          width="120"
          align="center"
        >
          <template #default="{ row }">
            <el-tag 
              :type="getCustomerTypeTagType(row.customerType)"
              size="small"
            >
              {{ getCustomerTypeText(row.customerType) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column 
          prop="customerName" 
          label="客户名称" 
          min-width="200"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="contractAmount" 
          label="合同金额" 
          width="130"
          align="right"
        >
          <template #default="{ row }">
            <span class="amount-text">
              ¥{{ formatCurrency(row.contractAmount) }}
            </span>
          </template>
        </el-table-column>
        
        <el-table-column 
          prop="manager" 
          label="业务经理" 
          width="120"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="creator" 
          label="合同拟制人" 
          width="120"
          show-overflow-tooltip
        />
        
        <el-table-column 
          prop="createTime" 
          label="拟制时间" 
          width="160"
          align="center"
        >
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column 
          label="操作" 
          width="160"
          fixed="right"
          align="center"
        >
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small"
              @click="handleReview(row)"
            >
              <i class="fas fa-eye"></i>
              审核
            </el-button>
            <el-button 
              type="danger" 
              size="small"
              @click="handleDelete(row)"
            >
              <i class="fas fa-trash"></i>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 审核弹窗 -->
    <el-dialog
      v-model="reviewDialogVisible"
      title="合同审核"
      width="90%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="review-dialog"
    >
      <div class="review-content" v-loading="reviewLoading">
        <!-- 基本信息卡片 -->
        <el-card class="info-card" shadow="never">
          <template #header>
            <div class="card-header">
              <i class="fas fa-info-circle"></i>
              <span>基本信息</span>
            </div>
          </template>
          
          <div class="info-grid">
            <div class="info-item">
              <label>报价单编号：</label>
              <span>{{ reviewData.quoteCode }}</span>
            </div>
            <div class="info-item">
              <label>客户代码：</label>
              <span>{{ reviewData.customerCode }}</span>
            </div>
            <div class="info-item">
              <label>客户名称：</label>
              <span>{{ reviewData.customerName }}</span>
            </div>
            <div class="info-item">
              <label>业务员：</label>
              <span>{{ reviewData.salesperson }}</span>
            </div>
            <div class="info-item">
              <label>合同编号：</label>
              <span>{{ reviewData.contractNumber }}</span>
            </div>
            <div class="info-item">
              <label>订单日期：</label>
              <span>{{ reviewData.orderDate }}</span>
            </div>
            <div class="info-item">
              <label>是否含税：</label>
              <span>{{ reviewData.isTaxIncluded === 1 ? '增值税票13%' : '否' }}</span>
            </div>
            <div class="info-item">
              <label>付款方式：</label>
              <span>{{ getPaymentMethodText(reviewData.paymentMethod) }}</span>
            </div>
            <div class="info-item">
              <label>报价总金额：</label>
              <span class="amount-text">¥{{ formatCurrency(reviewData.totalAmount) }}</span>
            </div>
            <div class="info-item">
              <label>含税总金额：</label>
              <span class="amount-text">¥{{ formatCurrency(reviewData.totalTaxAmount) }}</span>
            </div>
            <div class="info-item full-width">
              <label>备注：</label>
              <span>{{ reviewData.remark || '无' }}</span>
            </div>
          </div>
        </el-card>

        <!-- 物料明细列表 -->
        <el-card class="material-card" shadow="never" v-if="reviewData.items && reviewData.items.length > 0">
          <template #header>
            <div class="card-header">
              <i class="fas fa-list"></i>
              <span>物料明细</span>
            </div>
          </template>
          
          <el-table
            :data="reviewData.items"
            border
            stripe
            style="width: 100%"
            max-height="400"
          >
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="productName" label="产品名称" min-width="150" show-overflow-tooltip />
            <el-table-column prop="materialCode" label="物料编码" width="120" show-overflow-tooltip />
            <el-table-column prop="layerCount" label="层数" width="80" align="center" />
            <el-table-column prop="boardThickness" label="板厚" width="80" align="center" />
            <el-table-column prop="surfaceTreatment" label="表面处理" width="120" show-overflow-tooltip />
            <el-table-column prop="quantity" label="数量" width="80" align="right" />
            <el-table-column prop="unitPrice" label="单价" width="100" align="right">
              <template #default="{ row }">
                ¥{{ formatCurrency(row.unitPrice) }}
              </template>
            </el-table-column>
            <el-table-column prop="totalAmount" label="合计金额" width="120" align="right">
              <template #default="{ row }">
                ¥{{ formatCurrency(row.totalAmount) }}
              </template>
            </el-table-column>
            <el-table-column prop="deliveryDate" label="出货日期" width="120" align="center" />
            <el-table-column prop="itemRemark" label="备注" min-width="120" show-overflow-tooltip />
          </el-table>
        </el-card>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="reviewDialogVisible = false">
            <i class="fas fa-times"></i>
            关闭
          </el-button>
          <el-button 
            type="info" 
            @click="handlePrintPreview"
            :loading="printLoading"
          >
            <i class="fas fa-print"></i>
            打印预览
          </el-button>
          <el-button 
            type="success" 
            @click="handleApprove"
            :loading="approveLoading"
          >
            <i class="fas fa-check"></i>
            审核通过
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getEmployeeOptions,
  searchEmployees,
  getQuoteDetail
} from '@/api/quote'
import {
  getContractReviewList,
  deleteContract,
  approveContract,
  generateContractPDF,
  exportContracts
} from '@/api/contract'

// 响应式数据
const loading = ref(false)
const reviewLoading = ref(false)
const printLoading = ref(false)
const approveLoading = ref(false)
const selectedRows = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)
const tableData = ref([])

// 搜索表单
const searchForm = reactive({
  contractNumber: '',
  customerCode: '',
  customerName: '',
  createDateRange: [],
  manager: '',
  creator: ''
})

// 选项数据
const managerOptions = ref([])
const creatorOptions = ref([])

// 搜索状态
const managerLoading = ref(false)
const creatorLoading = ref(false)

// 审核弹窗
const reviewDialogVisible = ref(false)
const reviewData = ref({})

// 模拟测试数据
const mockData = [
  {
    id: 1,
    contractNumber: 'CT202412190001',
    customerCode: 'CUS001',
    customerType: 'A',
    customerName: '华为技术有限公司',
    contractAmount: 158000.00,
    manager: '张经理',
    creator: '李业务员',
    createTime: '2024-12-19 10:30:00',
    quoteId: 1
  },
  {
    id: 2,
    contractNumber: 'CT202412190002',
    customerCode: 'CUS002',
    customerType: 'B',
    customerName: '小米科技有限公司',
    contractAmount: 89500.00,
    manager: '王经理',
    creator: '赵业务员',
    createTime: '2024-12-19 14:20:00',
    quoteId: 2
  },
  {
    id: 3,
    contractNumber: 'CT202412190003',
    customerCode: 'CUS003',
    customerType: 'A',
    customerName: '比亚迪股份有限公司',
    contractAmount: 236000.00,
    manager: '李经理',
    creator: '张业务员',
    createTime: '2024-12-19 16:45:00',
    quoteId: 3
  },
  {
    id: 4,
    contractNumber: 'CT202412190004',
    customerCode: 'CUS004',
    customerType: 'C',
    customerName: '大疆创新科技有限公司',
    contractAmount: 125600.00,
    manager: '陈经理',
    creator: '周业务员',
    createTime: '2024-12-19 09:15:00',
    quoteId: 4
  },
  {
    id: 5,
    contractNumber: 'CT202412190005',
    customerCode: 'CUS005',
    customerType: 'B',
    customerName: '腾讯科技有限公司',
    contractAmount: 178900.00,
    manager: '刘经理',
    creator: '吴业务员',
    createTime: '2024-12-18 15:30:00',
    quoteId: 5
  }
]

// 计算属性
const searchParams = computed(() => {
  const params = {
    page: currentPage.value,
    size: pageSize.value
  }
  
  // 添加搜索条件
  if (searchForm.contractNumber) {
    params.contractNumber = searchForm.contractNumber
  }
  
  if (searchForm.customerCode) {
    params.customerCode = searchForm.customerCode
  }
  
  if (searchForm.customerName) {
    params.customerName = searchForm.customerName
  }
  
  if (searchForm.manager) {
    params.manager = searchForm.manager
  }
  
  if (searchForm.creator) {
    params.creator = searchForm.creator
  }
  
  if (searchForm.createDateRange && searchForm.createDateRange.length === 2) {
    params.startDate = searchForm.createDateRange[0]
    params.endDate = searchForm.createDateRange[1]
  }
  
  return params
})

// 格式化货币
const formatCurrency = (amount) => {
  if (!amount && amount !== 0) return '0.00'
  return Number(amount).toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取客户类型标签类型
const getCustomerTypeTagType = (type) => {
  const typeMap = {
    'A': 'success',
    'B': 'warning', 
    'C': 'info'
  }
  return typeMap[type] || 'info'
}

// 获取客户类型文本
const getCustomerTypeText = (type) => {
  const typeMap = {
    'A': 'A类客户',
    'B': 'B类客户',
    'C': 'C类客户'
  }
  return typeMap[type] || type
}

// 获取付款方式文本
const getPaymentMethodText = (method) => {
  const methodMap = {
    'CASH': '现金',
    'MONTHLY_30': '月结30天',
    'MONTHLY_60': '月结60天'
  }
  return methodMap[method] || method
}

// 业务经理搜索方法
const handleManagerSearch = async (query) => {
  if (!query || query.trim() === '') {
    await loadManagerOptions()
    return
  }
  
  managerLoading.value = true
  try {
    const response = await searchEmployees(query.trim())
    if (response.code === 200 && response.data) {
      if (response.data.records) {
        managerOptions.value = response.data.records.map(item => ({
          value: item.employeeName,
          label: item.employeeName
        }))
      } else if (Array.isArray(response.data)) {
        managerOptions.value = response.data.map(item => ({
          value: item.employeeName,
          label: item.employeeName
        }))
      }
    }
  } catch (error) {
    console.error('搜索业务经理失败:', error)
    // 使用默认数据
    managerOptions.value = [
      { value: '张经理', label: '张经理' },
      { value: '王经理', label: '王经理' },
      { value: '李经理', label: '李经理' }
    ]
  } finally {
    managerLoading.value = false
  }
}

// 拟制人搜索方法
const handleCreatorSearch = async (query) => {
  if (!query || query.trim() === '') {
    await loadCreatorOptions()
    return
  }
  
  creatorLoading.value = true
  try {
    const response = await searchEmployees(query.trim())
    if (response.code === 200 && response.data) {
      if (response.data.records) {
        creatorOptions.value = response.data.records.map(item => ({
          value: item.employeeName,
          label: item.employeeName
        }))
      } else if (Array.isArray(response.data)) {
        creatorOptions.value = response.data.map(item => ({
          value: item.employeeName,
          label: item.employeeName
        }))
      }
    }
  } catch (error) {
    console.error('搜索拟制人失败:', error)
    // 使用默认数据
    creatorOptions.value = [
      { value: '李业务员', label: '李业务员' },
      { value: '赵业务员', label: '赵业务员' },
      { value: '张业务员', label: '张业务员' }
    ]
  } finally {
    creatorLoading.value = false
  }
}

// 加载业务经理选项
const loadManagerOptions = async (keyword = '') => {
  try {
    const response = await getEmployeeOptions(keyword)
    if (response.code === 200 && response.data) {
      if (response.data.records) {
        managerOptions.value = response.data.records.map(item => ({
          value: item.employeeName,
          label: item.employeeName
        }))
      } else if (Array.isArray(response.data)) {
        managerOptions.value = response.data.map(item => ({
          value: item.employeeName,
          label: item.employeeName
        }))
      }
    }
  } catch (error) {
    console.error('加载业务经理选项失败:', error)
    // 使用默认数据
    managerOptions.value = [
      { value: '张经理', label: '张经理' },
      { value: '王经理', label: '王经理' },
      { value: '李经理', label: '李经理' },
      { value: '陈经理', label: '陈经理' },
      { value: '刘经理', label: '刘经理' }
    ]
  }
}

// 加载拟制人选项
const loadCreatorOptions = async (keyword = '') => {
  try {
    const response = await getEmployeeOptions(keyword)
    if (response.code === 200 && response.data) {
      if (response.data.records) {
        creatorOptions.value = response.data.records.map(item => ({
          value: item.employeeName,
          label: item.employeeName
        }))
      } else if (Array.isArray(response.data)) {
        creatorOptions.value = response.data.map(item => ({
          value: item.employeeName,
          label: item.employeeName
        }))
      }
    }
  } catch (error) {
    console.error('加载拟制人选项失败:', error)
    // 使用默认数据
    creatorOptions.value = [
      { value: '李业务员', label: '李业务员' },
      { value: '赵业务员', label: '赵业务员' },
      { value: '张业务员', label: '张业务员' },
      { value: '周业务员', label: '周业务员' },
      { value: '吴业务员', label: '吴业务员' }
    ]
  }
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // 调用后端API获取合同审核列表
    const response = await getContractReviewList(searchParams.value)
    
    if (response.code === 200) {
      tableData.value = response.data.records || []
      total.value = response.data.total || 0
      currentPage.value = response.data.current || 1
      pageSize.value = response.data.size || 20
    } else {
      ElMessage.error(response.message || '获取合同审核列表失败')
    }
  } catch (error) {
    console.error('获取合同审核列表失败:', error)
    ElMessage.error('获取合同审核列表失败，使用模拟数据')
    
    // 发生错误时使用模拟数据
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 应用搜索过滤
    let filteredData = [...mockData]
    
    if (searchForm.contractNumber) {
      filteredData = filteredData.filter(item => 
        item.contractNumber.toLowerCase().includes(searchForm.contractNumber.toLowerCase())
      )
    }
    
    if (searchForm.customerCode) {
      filteredData = filteredData.filter(item => 
        item.customerCode.toLowerCase().includes(searchForm.customerCode.toLowerCase())
      )
    }
    
    if (searchForm.customerName) {
      filteredData = filteredData.filter(item => 
        item.customerName.toLowerCase().includes(searchForm.customerName.toLowerCase())
      )
    }
    
    if (searchForm.manager) {
      filteredData = filteredData.filter(item => 
        item.manager === searchForm.manager
      )
    }
    
    if (searchForm.creator) {
      filteredData = filteredData.filter(item => 
        item.creator === searchForm.creator
      )
    }
    
    // 模拟分页
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    tableData.value = filteredData.slice(start, end)
    total.value = filteredData.length
  } finally {
    loading.value = false
  }
}

// 事件处理函数
const handleSearch = () => {
  currentPage.value = 1
  loadData()
}

const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    if (key === 'createDateRange') {
      searchForm[key] = []
    } else {
      searchForm[key] = ''
    }
  })
  currentPage.value = 1
  loadData()
}

const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadData()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadData()
}

// 审核操作
const handleReview = async (row) => {
  reviewLoading.value = true
  reviewDialogVisible.value = true
  
  try {
    // 根据合同关联的报价单ID获取详细信息
    const response = await getQuoteDetail(row.quoteId)
    
    if (response.code === 200) {
      reviewData.value = response.data
    } else {
      // 使用模拟数据
      reviewData.value = {
        quoteCode: 'QT202412190001',
        customerCode: row.customerCode,
        customerName: row.customerName,
        salesperson: row.manager,
        contractNumber: row.contractNumber,
        orderDate: '2024-12-19',
        isTaxIncluded: 1,
        paymentMethod: 'MONTHLY_30',
        totalAmount: row.contractAmount,
        totalTaxAmount: row.contractAmount * 1.13,
        remark: '常规PCB订单，按标准工艺生产',
        items: [
          {
            productName: '4层PCB板',
            materialCode: 'PCB4L001',
            layerCount: '4层',
            boardThickness: '1.6mm',
            surfaceTreatment: '无铅喷锡',
            quantity: 1000,
            unitPrice: 8.50,
            totalAmount: 8500.00,
            deliveryDate: '2024-12-30',
            itemRemark: '标准工艺'
          },
          {
            productName: '6层PCB板',
            materialCode: 'PCB6L002',
            layerCount: '6层',
            boardThickness: '2.0mm',
            surfaceTreatment: '沉金',
            quantity: 500,
            unitPrice: 15.80,
            totalAmount: 7900.00,
            deliveryDate: '2025-01-05',
            itemRemark: '高精度要求'
          }
        ]
      }
    }
  } catch (error) {
    console.error('获取报价单详情失败:', error)
    ElMessage.error('获取报价单详情失败')
  } finally {
    reviewLoading.value = false
  }
}

// 删除操作
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除合同编号为 "${row.contractNumber}" 的合同吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用后端删除API
    const response = await deleteContract(row.id)
    
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadData()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败，请检查网络连接')
    }
  }
}

// 审核通过
const handleApprove = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要审核通过该合同吗？',
      '审核确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    approveLoading.value = true
    
    // 调用后端审核通过API
    const response = await approveContract(reviewData.value.id)
    
    if (response.code === 200) {
      ElMessage.success('审核通过成功')
      reviewDialogVisible.value = false
      loadData()
    } else {
      ElMessage.error(response.message || '审核失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审核失败:', error)
      ElMessage.error('审核失败，请检查网络连接')
    }
  } finally {
    approveLoading.value = false
  }
}

// 打印预览
const handlePrintPreview = async () => {
  printLoading.value = true
  
  try {
    // 调用打印预览API或生成PDF
    const response = await generateContractPDF(reviewData.value.id)
    
    // 创建blob URL并打开新窗口
    const blob = new Blob([response], { type: 'application/pdf' })
    const url = window.URL.createObjectURL(blob)
    window.open(url, '_blank')
    
    ElMessage.success('正在打开打印预览...')
  } catch (error) {
    console.error('打印预览失败:', error)
    ElMessage.error('打印预览失败，请检查网络连接')
  } finally {
    printLoading.value = false
  }
}

// 导出数据
const handleExport = async () => {
  try {
    // 调用导出API
    const response = await exportContracts(searchParams.value)
    
    // 创建下载链接
    const blob = new Blob([response], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `合同审核列表_${new Date().toISOString().slice(0, 10)}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请检查网络连接')
  }
}

// 加载基础数据
const loadBaseData = async () => {
  try {
    await Promise.all([
      loadManagerOptions(),
      loadCreatorOptions()
    ])
  } catch (error) {
    console.error('加载基础数据失败:', error)
  }
}

// 页面初始化
onMounted(async () => {
  await loadBaseData()
  loadData()
})
</script>

<style scoped>
.contract-review-container {
  padding: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.search-card {
  border-radius: 6px;
  flex-shrink: 0;
}

.search-card :deep(.el-card__body) {
  padding: 16px;
}

.search-form {
  margin-bottom: 0;
}

.search-form :deep(.el-form-item) {
  margin-bottom: 12px;
  margin-right: 16px;
}

.table-card {
  border-radius: 6px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.table-card :deep(.el-card__body) {
  padding: 16px;
  display: flex;
  flex-direction: column;
  flex: 1;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.table-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  display: flex;
  align-items: center;
  gap: 8px;
}

.table-actions {
  display: flex;
  gap: 8px;
}

.amount-text {
  font-weight: 600;
  color: #e6a23c;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

/* 审核弹窗样式 */
.review-dialog :deep(.el-dialog__body) {
  padding: 0 20px 20px;
}

.review-content {
  max-height: 70vh;
  overflow-y: auto;
}

.info-card,
.material-card {
  margin-bottom: 16px;
}

.info-card :deep(.el-card__body),
.material-card :deep(.el-card__body) {
  padding: 16px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #333;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  align-items: center;
}

.info-item {
  display: flex;
  align-items: center;
}

.info-item.full-width {
  grid-column: 1 / -1;
}

.info-item label {
  font-weight: 600;
  color: #666;
  margin-right: 8px;
  min-width: 100px;
  flex-shrink: 0;
}

.info-item span {
  color: #333;
  flex: 1;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

@media (max-width: 1200px) {
  .info-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .table-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
}
</style> 